import socket

def fetch_url_content(url):
    # 解析URL以获取主机名和路径
    parts = url.split('/')
    host = parts[2]
    path = '/' + '/'.join(parts[3:])

    # 创建一个socket对象
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 连接到服务器
        s.connect((host, 80))

        # 构建HTTP请求头
        request = f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"

        # 发送HTTP请求
        s.send(request.encode('utf-8'))

        # 接收响应数据
        response = b""
        while True:
            part = s.recv(1024)
            if not part:
                break
            response += part

        # 关闭socket连接
        s.close()

        response_str = response.decode('utf-8', errors='ignore') 

        return response_str

    except socket.error as e:
        print(f"Socket error: {e}")
        return None

# 目标网页的URL
url = 'http://www.people.com.cn'

# 获取网页内容
content = fetch_url_content(url)

# 保存到文件
if content:
    with open('webpage_content.txt', 'w', encoding='utf-8') as file:
        file.write(content)
    print("网页内容已保存到webpage_content.txt文件中。")
else:
    print("无法获取网页内容。")